package com.zhao.mock;

import com.zhao.utils.CommonUtils;

import java.io.*;
import java.util.LinkedList;
import java.util.List;


/**
 * Description: 模拟实时产生的数据,写入到游戏日志文件中<br/>
 * 造数的程序开启线程-->向日志中实时写入数据(对应的业务场景:游戏玩家玩游戏时,实时向日志文件中写入数据)
 * @author 柒柒
 * @version : 1.0
 * @ClassName MockRealTimeData <br/>
 * Copyright (c) ，2020 ， 赵 <br/>
 * Date： 2020/12/11 16:00
 */

public class MockRealTimeData extends Thread{

    public static void main(String[] args) {
        new MockRealTimeData().start();
    }

    @Override
    public void run() {
        List<String> container = readGameGlog2Buffer();
        String targetFile = "a_head/output/gameRealTimeLog.txt";

        BufferedWriter bw = null;

        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile),"GB2312"));
            int index = 0;
            while (true){
                //计数
                String log = container.get(index++);
                //1.读取指定集合中的日志信息
                //2.写入指定的日志文件
                bw.write(log);
                bw.newLine();
                bw.flush();

                //sleep
                CommonUtils.mySleep(1);
                //若是计数器中的值与集合长度相同,重新读取文件中的数据
                if (index == container.size()){
                    index = 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将游戏日志文件中的数据读入StringBuffer中
     * @return
     */
    private static List<String> readGameGlog2Buffer(){
        List<String> buffer = new LinkedList<>();
        File dir = new File("a_head/input");

        File[] dirs = dir.listFiles();
        for (File tmpDir: dirs){
            File[] logFiles = tmpDir.listFiles();
            for (File file: logFiles){
                BufferedReader reader = null;

                try {
                    reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GB2312"));
                    String line = null;
                    while ((line = reader.readLine()) != null){
                        buffer.add(line);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (reader != null){
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return buffer;
    }
}



















